package com.zyf.baselibrary.base

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.*
import com.example.baselibrary.utlis.AppCache
import com.example.httplibrary.https.ApiService
import com.example.httplibrary.https.RetrofitClient
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow

/**
 * 封装导航事件类型
 */
sealed class NavigationEvent {
    data class StartActivity(
        val target: Class<out Activity>,
        val bundle: Bundle? = null,
        val requestCode: Int? = null
    ) : NavigationEvent()

    object Finish : NavigationEvent()
    object FinishWithResult : NavigationEvent()
    object BackPressed : NavigationEvent()
}

/**
 * 基础ViewModel接口
 */
interface IBaseViewModel {
    fun onCreate(owner: LifecycleOwner) {}
    fun onStart(owner: LifecycleOwner) {}
    fun onResume(owner: LifecycleOwner) {}
    fun onPause(owner: LifecycleOwner) {}
    fun onStop(owner: LifecycleOwner) {}
    fun onDestroy(owner: LifecycleOwner) {}
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}
}

/**
 * 基础ViewModel实现
 */
abstract class BaseViewModel : ViewModel(), IBaseViewModel, DefaultLifecycleObserver {
    // 每次都获取新的服务实例
    protected var apiService = RetrofitClient.createService(ApiService::class.java)
    // 使用SharedFlow确保导航事件只被消费一次
    private val _navigationEvent = MutableSharedFlow<NavigationEvent>(replay = 0)
    val navigationEvent = _navigationEvent.asSharedFlow()
    val mAcache = AppCache.get()
    // 状态管理
    private val _loadingState = MutableLiveData<Boolean>()
    val loadingState: LiveData<Boolean> = _loadingState

    override fun onCreate(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onCreate(owner)
    override fun onStart(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onStart(owner)
    override fun onResume(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onResume(owner)
    override fun onPause(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onPause(owner)
    override fun onStop(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onStop(owner)
    override fun onDestroy(owner: LifecycleOwner) = super<DefaultLifecycleObserver>.onDestroy(owner)

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) = Unit

    /**
     * 显示加载状态
     */
    protected fun showLoading() {
        _loadingState.value = true
    }

    /**
     * 隐藏加载状态
     */
    protected fun hideLoading() {
        _loadingState.value = false
    }

    /**
     * 启动Activity
     */
    protected suspend fun navigateTo(
        target: Class<out Activity>,
        bundle: Bundle? = null,
        requestCode: Int? = null
    ) {
        _navigationEvent.emit(NavigationEvent.StartActivity(target, bundle, requestCode))
    }


    /**
     * 关闭当前界面
     */
    protected suspend fun finish() {
        _navigationEvent.emit(NavigationEvent.Finish)
    }

    /**
     * 关闭并返回结果
     */
    protected suspend fun finishWithResult() {
        _navigationEvent.emit(NavigationEvent.FinishWithResult)
    }

    /**
     * 返回按键事件
     */
    protected suspend fun onBackPressed() {
        _navigationEvent.emit(NavigationEvent.BackPressed)
    }

    companion object {
        /**
         * 提供ViewModel的工厂方法
         */
        inline fun <reified VM : BaseViewModel> createFactory(
            crossinline create: () -> VM
        ): ViewModelProvider.Factory {
            return object : ViewModelProvider.Factory {
                @Suppress("UNCHECKED_CAST")
                override fun <T : ViewModel> create(modelClass: Class<T>): T {
                    return create() as T
                }
            }
        }
    }
}